package com.laizt.client.openexe;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.laizt.client.util.IpUtils;
import com.laizt.client.util.ShareFileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class OpenExeServer {
    private static final Logger logger = LoggerFactory.getLogger(OpenExeServer.class.getName());
    private ConcurrentHashMap<String, Object> devMap = new ConcurrentHashMap<String, Object>();
    public OpenExeServer() {
        new Thread(new OpenExeServer.SocketAccept()).start();
    }

    /**
     * 阻塞线程，接收请求
     */
    class SocketAccept implements Runnable {
        public void run(){
            try {
                int port = 8885;
                logger.info("监听的端口号:"+port);
                ServerSocket ss = new ServerSocket(8885,200);
                while(true){
                    logger.info("等待打开Exe程序连接请求.....");
                    Socket s = ss.accept();
                    new Thread(new OpenExeServer.SocketAction(s)).start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 打开本地exe工作线程
     */
    class SocketAction implements Runnable{
        Socket client;
        public SocketAction(Socket client) {
            this.client = client;
        }
        public void run() {
            logger.info("打开本地Exe线程开始运行");
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("code","00");
            resultMap.put("msg","打开测试软件成功！");
            try {
                InputStream in = client.getInputStream();
                //获取Ip和共享路径，并打开本地exe
                byte[]  b = new byte[2048];
                in.read(b);
                String msg = new String(b,"UTF-8").trim();
                logger.info("Exe服务端获取到的数据："+msg);
                Map<String,Object> map = (Map<String, Object>) JSONObject.parse(msg);
                logger.info("本地Ip:"+IpUtils.getIp());
                logger.info("测试软件将要保存的本地目录:"+map.get("dir"));
                logger.info("浏览器请求IP:"+map.get("ip"));
                logger.info("测试软件请求服务器的端口:"+map.get("port"));
                logger.info("共享服务器的ip："+map.get("remoteIp"));
                logger.info("共享目录的路径："+map.get("remoteUrl"));
                //如果用户明不为空，需要处理url请求
                if(map.get("remoteIp")!=null){
                    logger.info("开始处理请求地址...");
                    ShareFileUtils.dealUrl(map);
                }
                OpenExeClient.ExeMain(resultMap,map,client.getInetAddress().getHostAddress());
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(IpUtils.getIp()+"打开本地Exe线程异常,结束");
            }finally {
                logger.info("响应信息:"+ JSONUtils.toJSONString(resultMap));
                try {
                    OutputStreamWriter outSW = null;
                    outSW = new OutputStreamWriter(client.getOutputStream(), "UTF-8");
                    outSW.write(JSONUtils.toJSONString(resultMap));
                    outSW.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                overThis();
            }
            logger.info(IpUtils.getIp()+"打开本地Exe线程结束");
        }

        /**
         * 关闭Exe线程
         */
        private void overThis() {
            if(client!=null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            logger.info("关闭Exe接收连接："+client.getInetAddress().getHostAddress());
        }
    }

}
